package com.hitsz.cdq;

import android.app.Fragment;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatDelegate;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.hitsz.cdq.MainActivity.APP_ACK_ALL;
import static com.hitsz.cdq.MainActivity.APP_ACK_STATE;
import static com.hitsz.cdq.MainActivity.IP_ADDRESS_SERVER;
import static com.hitsz.cdq.MainActivity.PASSWORD;
import static com.hitsz.cdq.MainActivity.USER;
import static com.hitsz.cdq.MainActivity.data_from_server;
import static com.hitsz.cdq.MainActivity.dbUtils;
import static com.hitsz.cdq.MainActivity.inputStream;
import static com.hitsz.cdq.MainActivity.outputStream;

/**
 * Created by ChenDongqiang on 2017/6/26.
 */
public class TaskAdminFragment extends Fragment {

    private ListView list;
    private List<task_info> mlistInfo = new ArrayList<task_info>();
    private Connection mysql_conn;

    private int img_task = R.drawable.image_task;
    private String sql = "select * from task";

    private Boolean isRunning = false;
    private boolean is_thread_end;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.content_task_admin, container, false);
        list = (ListView) view.findViewById(R.id.list_admin);
        isRunning=true;
        getDataFromServerDB(view);
        return view;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isRunning=false;
        while (!is_thread_end) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    ///////////////////////////////////////服务器数据库连接////////////////////////////////////////
    public void getDataFromServerDB(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isRunning) {
                    is_thread_end=false;
                    Log.i("onConn", "onConn");
                    mysql_conn = MySqlUtil.openConnection("jdbc:mysql://" + IP_ADDRESS_SERVER + "/smart_car", USER, PASSWORD);
                    if (mysql_conn == null) {
                        Log.i("onConn", "服务器数据库连接失败");
                        return;
                    }
                    Statement statement = null;
                    ResultSet result = null;
                    mlistInfo.clear();
                    try {
                        statement = mysql_conn.createStatement();
                        result = statement.executeQuery(sql);
                        System.out.println(result);
                        if (result != null && result.first()) {
                            int idColumnIndex = result.findColumn("id");
                            int nameColumnIndex = result.findColumn("goods_name");
                            int typeColumnIndex = result.findColumn("goods_category");
                            int startColumnIndex = result.findColumn("start");
                            int endColumnIndex = result.findColumn("end");
                            int update_timeColumnIndex = result.findColumn("update_time");

                            while (!result.isAfterLast()) {
                                task_info m_task_info = new task_info();
                                m_task_info.setId(result.getString(idColumnIndex));
                                m_task_info.setName(result.getString(nameColumnIndex));
                                m_task_info.setGoodsCategory(result.getString(typeColumnIndex));
                                m_task_info.setStart(result.getString(startColumnIndex));
                                m_task_info.setEnd(result.getString(endColumnIndex));
                                m_task_info.setUpdate_time(result.getString(update_timeColumnIndex));
                                m_task_info.setImg(img_task);
                                mlistInfo.add(m_task_info);
                                System.out.println(result.getString(update_timeColumnIndex));
                                result.next();
                            }

                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mlistInfo != null) {
                                        list.setAdapter(new ListViewAdapter(mlistInfo));
                                    }
                                }
                            });

                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (result != null) {
                                result.close();
                            }
                            if (statement != null) {
                                statement.close();
                            }
                        } catch (SQLException sqle) {
                            sqle.printStackTrace();
                        }
                    }
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                is_thread_end=true;
            }
        }
        ).start();

    }


    private class ListViewAdapter extends BaseAdapter {
        View[] itemViews;

        public ListViewAdapter(List<task_info> mlistInfo) {
            int len = mlistInfo.size();
            System.out.println("mlistInfo_size=" + len);
            itemViews = new View[len];
            for (int i = 0; i < mlistInfo.size(); i++) {
                task_info getInfo = (task_info) mlistInfo.get(i);    //获取第i个对象
                //调用makeItemView，实例化一个Item
                itemViews[i] = makeItemView(
                        getInfo.getName(), getInfo.getState()
                );
            }
        }

        public int getCount() {
            return itemViews.length;
        }

        public View getItem(int position) {
            return itemViews[position];
        }

        public long getItemId(int position) {
            return position;
        }

        //绘制Item的函数
        private View makeItemView(String strTitle, String strText) {
            LayoutInflater inflater = (LayoutInflater) TaskAdminFragment.this.getActivity()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            // 使用View的对象itemView与R.layout.item关联
            View itemView = inflater.inflate(R.layout.content_task_admin_item, null);

            // 通过findViewById()方法实例R.layout.item内各组件
            TextView name = (TextView) itemView.findViewById(R.id.tv_goods_name);
            name.setText(strTitle);    //填入相应的值
            TextView goods_save = (TextView) itemView.findViewById(R.id.tv_goods_save);
            goods_save.setText(strText);
            return itemView;
        }


        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null)
                return itemViews[position];
            return convertView;
        }


    }
}
